<script setup lang="ts">
import { reactive, computed, onMounted, useTemplateRef } from 'vue'
import { avatarList } from '@/common'
import { StorageEnum } from '@common/enums'
import { updateDetails, getUserDetail } from '@/api/user'
import UpdateUserInfoDialog from './update-user-info-dialog.vue'
import AvatarDialog from './avatar-dialog.vue'
import { ElMessage } from 'element-plus'
import { queryAccomplish } from '@/api/todo'
import type { UserResponse } from '@interface'

defineOptions({
  name: 'UserCard_component',
})

// 从缓存中获取用户id
const userId = JSON.parse(localStorage.getItem(StorageEnum.USER_ID) as string)
// 切换用户头像的弹窗
const avatarDialogRef =
  useTemplateRef<InstanceType<typeof AvatarDialog>>('avatarDialogRef')
// 用户基本信息
const userInfo = reactive<Partial<UserResponse>>({})

// 获取用户基本信息
const initGetUserInfo = async () => {
  if (!userId) return
  const result = await getUserDetail({ id: userId })
  // console.log(result)
  Object.assign(userInfo, result)
}
onMounted(initGetUserInfo)

/**
 * 因为用户头像是使用的数字方式进行存储
 * 所以这里需要在列表里面进行查找
 * 找到对应的url
 */
const avatar = computed(() => {
  if (!userInfo.avatar) return avatarList[0].avatar
  return avatarList.find((item) => item.id === userInfo.avatar)?.avatar
})

const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '已经很晚了，注意休息'
  if (hour < 9) return '早上好，新的一天开始了'
  if (hour < 12) return '上午好，工作顺利'
  if (hour < 14) return '中午好'
  if (hour < 17) return '下午好，工作顺利'
  if (hour < 19) return '傍晚好'
  return '晚上好，注意休息'
})

// 获取待办占比
const todoAccomplish = reactive<{
  unfinished: number
  complete: number
}>({
  unfinished: 0,
  complete: 0,
})
const queryTodoAccomplish = async () => {
  if (!userId) return
  const result = await queryAccomplish({ createdBy: userId })
  Object.assign(todoAccomplish, result)
  // console.log('🌈 —— data-result --->', result)
}
onMounted(queryTodoAccomplish)

const updateUserInfoRef =
  useTemplateRef<InstanceType<typeof UpdateUserInfoDialog>>('updateUserInfoRef')

// 打开更新用户信息弹窗
const openUserInfoDialog = () => {
  updateUserInfoRef.value?.open()
}

// 更新用户信息
const handleUpdateUserInfo = async (userInfo: any) => {
  if (Array.isArray(userInfo.tags)) {
    userInfo.tags = userInfo.tags.join('&')
  }
  await updateDetails(userInfo)
  ElMessage.success('更新成功')
  initGetUserInfo()
}

// 打开切换头像的弹窗
const openAvatarDialogHandler = (_avatar: string | undefined) => {
  updateUserInfoRef.value?.close()
  avatarDialogRef.value?.open()
}

const handleAvatarDialog = (avatar: string) => {
  // console.log(avatar)
  userInfo.avatar = avatar
  avatarDialogRef.value?.close()
  updateUserInfoRef.value?.open()
}

const handleAvatarDialogClose = () => {
  avatarDialogRef.value?.close()
  updateUserInfoRef.value?.open()
}
</script>

<template>
  <div class="user-card">
    <div class="card-content" v-loading="false">
      <div class="avatar">
        <el-avatar :size="90" :src="avatar" />
        <div class="point">
          <div class="point-success"></div>
          <!-- <div class="point-warning"></div> -->
        </div>
      </div>
      <div class="user-details">
        <div class="greeting-nickname">
          <div class="greeting">{{ greeting }}</div>
          <div>{{ userInfo.nickName }}</div>
          <div class="edit" @click="openUserInfoDialog">
            <el-icon size="16"><Edit /></el-icon>
          </div>
        </div>
        <div class="signature">
          signature: {{ userInfo.signature || '暂无个性签名' }}
        </div>
        <div class="tags">
          <el-tag
            v-for="tag in userInfo.tags || []"
            :key="tag"
            size="small"
            class="tag-item"
            effect="dark"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>

      <div class="right-section">
        <div class="todo-section">
          <div class="section-title">
            <el-icon color="#409eff"><List /></el-icon>
            <span>待办</span>
            <span
              ><span style="color: #409eff">
                {{ todoAccomplish.complete }}
              </span>
              / {{ todoAccomplish.unfinished }}</span
            >
          </div>
        </div>
      </div>
    </div>
  </div>

  <UpdateUserInfoDialog
    ref="updateUserInfoRef"
    :userInfo="userInfo"
    @openAvatarDialog="openAvatarDialogHandler"
    @confirmProcessor="handleUpdateUserInfo"
  />

  <AvatarDialog
    ref="avatarDialogRef"
    :avatar="userInfo.avatar"
    @closeProcessor="handleAvatarDialogClose"
    @confirmProcessor="handleAvatarDialog"
  />
</template>

<style scoped lang="scss">
.user-card {
  width: 100%;
  height: 140px;
  padding: 24px;
  background-color: #1a1a1a;
  border-radius: 12px;
  color: #fff;
  border: 1px solid var(--xfxjLineColor);

  .card-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    gap: 24px;

    .avatar {
      width: 90px;
      height: 90px;
      border-radius: 50%;
      position: relative;

      .point {
        width: 15px;
        height: 15px;
        background-color: #fff;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        bottom: 5px;
        right: 5px;

        .point-success {
          width: 10px;
          height: 10px;
          background-color: #67c23a;
          border-radius: 50%;
        }

        .point-warning {
          width: 10px;
          height: 10px;
          background-color: #f56c6c;
          border-radius: 50%;
        }
      }
    }

    .user-details {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      gap: 6px;

      .greeting-nickname {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 20px;

        .greeting {
          color: #409eff;
          font-weight: 600;
        }

        .edit {
          width: 33px;
          height: 33px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            color: #409eff;
          }
        }
      }

      .signature {
        font-size: 14px;
        color: #a0a0a0;
      }

      .tags {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;

        .tag-item {
          border: none;
          cursor: pointer;
        }
      }
    }

    .right-section {
      flex: 1;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 32px;

      .todo-section {
        font-size: 32px;
        font-weight: 600;

        .section-title {
          display: flex;
          align-items: center;
          gap: 6px;
        }
      }
    }
  }
}
</style>
